import httpx
from app.config import settings
from app.utils.logger import logger
import json

class TextLLMService:
    """通用文本大模型服务（OpenAI兼容 /v1/chat/completions）"""
    def __init__(self):
        self.base_url = settings.TEXT_LLM_BASE_URL.rstrip("/") if settings.TEXT_LLM_BASE_URL else ""
        self.api_key = settings.TEXT_LLM_API_KEY or ""
        self.model = settings.TEXT_LLM_MODEL or "gpt-4o-mini"
        self.timeout = float(settings.TEXT_LLM_TIMEOUT) if getattr(settings, 'TEXT_LLM_TIMEOUT', None) else 120.0

    def _is_enabled(self) -> bool:
        return bool(self.base_url and self.api_key and self.model)

    async def analyze_text(self, prompt: str) -> str:
        if not self._is_enabled():
            raise Exception("TextLLMService 未配置：请设置 TEXT_LLM_BASE_URL/TEXT_LLM_API_KEY/TEXT_LLM_MODEL 并将 PROMPT_TEXT_PROVIDER=openai")

        url = f"{self.base_url}/v1/chat/completions"
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}",
            "Accept": "application/json"
        }
        payload = {
            "model": self.model,
            "messages": [
                {"role": "user", "content": prompt}
            ],
            "stream": False,
            "temperature": 0.7,
            "max_tokens": 1024
        }

        logger.info(f"TextLLM 文本分析请求 -> {url}, model={self.model}")
        try:
            async with httpx.AsyncClient(timeout=self.timeout) as client:
                resp = await client.post(url, headers=headers, json=payload)
        except httpx.ReadTimeout:
            # 暂不重试，抛清晰错误，交由上层兜底
            raise Exception(f"TextLLM 请求超时(>{self.timeout}s): {url}")

        if resp.status_code != 200:
            msg = f"TextLLM 请求失败: {resp.status_code} {resp.text[:500]}"
            logger.error(msg)
            raise Exception(msg)

        data = resp.json()
        logger.info(f"TextLLM 响应简要: keys={list(data.keys()) if isinstance(data, dict) else type(data)}")
        # 兼容多种常见返回格式
        if isinstance(data, dict):
            # 1) 标准 Chat Completions
            if 'choices' in data and data['choices']:
                choice = data['choices'][0]
                # message.content
                if isinstance(choice, dict) and 'message' in choice and isinstance(choice['message'], dict):
                    content = choice['message'].get('content', '')
                    if content:
                        return content.strip()
                # text（有些兼容网关复用 text 字段）
                if isinstance(choice, dict) and 'text' in choice and isinstance(choice['text'], str) and choice['text'].strip():
                    return choice['text'].strip()
            # 2) 兼容 response/output 字段
            if 'response' in data:
                resp_field = data['response']
                if isinstance(resp_field, str) and resp_field.strip():
                    return resp_field.strip()
                if isinstance(resp_field, list):
                    merged = "\n".join([x for x in resp_field if isinstance(x, str) and x.strip()])
                    if merged:
                        return merged.strip()
            if 'output' in data:
                out = data['output']
                if isinstance(out, str) and out.strip():
                    return out.strip()
                if isinstance(out, dict) and 'text' in out and isinstance(out['text'], str) and out['text'].strip():
                    return out['text'].strip()
        # 兜底返回原始JSON字符串，便于后续正则解析
        return json.dumps(data, ensure_ascii=False)